package com.alogic.xscript.plugins;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 对json对象的子对象进行遍历
 *
 * @since 1.6.12.50 [20191202 duanyy] <br>
 *
 * @version 1.6.14.15 [20210802 duanyy] <br>
 * - 增加循环跳出条件 <br>
 */
public class RepeatObj extends Segment{
    protected String key = "$key";
    protected String $break = "false";

    public RepeatObj(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        key = PropertiesConstants.getString(p,"key",key,true);
        $break = PropertiesConstants.getRaw(p,"break",$break);
    }

    @Override
    protected void onExecute(XsObject root,XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        if (current instanceof JsonObject){
            Map<String,Object> jsonMap = (Map<String, Object>) current.getContent();
            Iterator<Map.Entry<String,Object>> iter = jsonMap.entrySet().iterator();
            while (iter.hasNext()){
                Map.Entry<String,Object> entry = iter.next();
                Object val = entry.getValue();
                if (val instanceof Map<?,?>){
                    ctx.SetValue(key, entry.getKey());
                    super.onExecute(root, new JsonObject("current",(Map<String,Object>)val), ctx, watcher);
                }else{
                    if (val instanceof List<?>){
                        List<Object> list = (List<Object>)val;
                        for (Object obj:list){
                            if (obj instanceof Map<?,?>){
                                ctx.SetValue(key, entry.getKey());
                                super.onExecute(root, new JsonObject("current",(Map<String,Object>)obj), ctx, watcher);
                            }
                        }
                    }
                }
                if (PropertiesConstants.transform(ctx,$break,false)){
                    break;
                }
            }
        }else{
            throw new BaseException("core.e1000",
                    String.format("Tag %s does not support protocol %s",this.getXmlTag(),root.getClass().getName()));
        }
    }
}